package com.csxy.lsh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csxy.lsh.JwtUtils;
import com.csxy.lsh.R;
import com.csxy.lsh.api.UcenterClient;
import com.csxy.lsh.entity.EduComment;
import com.csxy.lsh.entity.vo.UcenterMemberVo;
import com.csxy.lsh.exception.MyException;
import com.csxy.lsh.service.EduCommentService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/eduservice/edu-comment")
public class EduCommentController {
    @Autowired
    private EduCommentService eduCommentService;

    @Autowired
    private UcenterClient ucenterClient;

    //查詢主貼回復列表
    @GetMapping("/getCommentPage/{page}/{limit}")
    public R getCommentPage(@PathVariable long page, @PathVariable long limit , String courseId) {
        QueryWrapper<EduComment> wrapper =new QueryWrapper<>();
        Page<EduComment> commentPage=new Page<>(page,limit);
        // 優化：courseId 不為空時查分類，為空時查全部
        if (!StringUtils.isEmpty(courseId)) {
            wrapper.eq("course_id", courseId);
        }
        wrapper.orderByDesc("gmt_create");

        eduCommentService.page(commentPage,wrapper);
        List<EduComment> commentList =commentPage.getRecords();
        long current = commentPage.getCurrent();
        long pages = commentPage.getPages();
        long size = commentPage.getSize();
        long total = commentPage.getTotal();
        boolean hasPrevious = commentPage.hasPrevious();
        boolean hasNext = commentPage.hasNext();
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", commentList);
        map.put("size", size);
        map.put("current", current);
        map.put("pages", pages);
        map.put("hasPrevious", hasPrevious);
        map.put("hasNext", hasNext);
        return R.ok().data(map);

    }
    //查詢主貼詳情
    @GetMapping("/getById/{id}")
    public R getById(@PathVariable String id) {
        EduComment comment = eduCommentService.getById(id);
        if (comment == null) {
            throw new MyException(20001, "评论不存在");
        }
        return R.ok().data("comment", comment);
    }

    //發表主貼回復
    @PostMapping("/auth/addComment")
        public R addcomment(HttpServletRequest request,@RequestBody EduComment eduComment){
        String memberId= JwtUtils.getMemberIdByJwtToken(request);

        if (StringUtils.isEmpty(memberId)){
            throw new MyException(20001,"请登录");
        }
        eduComment.setMemberId(memberId);

            UcenterMemberVo memberVo=ucenterClient.getMemberInfoById(memberId);

            eduComment.setAvatar(memberVo.getAvatar());
            eduComment.setNickname(memberVo.getNickname());

            eduCommentService.save(eduComment);

            return R.ok();
        }

    // 我的发帖（parent_id 为空或 null）
    @GetMapping("/myPosts")
    public R getMyPosts(HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            throw new MyException(20001, "请登录");
        }
        List<EduComment> posts = eduCommentService.list(
            new QueryWrapper<EduComment>()
                .eq("member_id", memberId)
                .and(wrapper -> wrapper.isNull("parent_id").or().eq("parent_id", ""))
        );
        return R.ok().data("list", posts);
    }

    // 我的回复（parent_id 不为空且不为 ""）
    @GetMapping("/myReplies")
    public R getMyReplies(HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) {
            throw new MyException(20001, "请登录");
        }
        List<EduComment> replies = eduCommentService.list(
            new QueryWrapper<EduComment>()
                .eq("member_id", memberId)
                .isNotNull("parent_id")
                .ne("parent_id", "")
        );
        return R.ok().data("list", replies);
    }

    // 刪除評論
    @PostMapping("/delete/{id}")
    public R delete(@PathVariable String id) {
        boolean removed = eduCommentService.removeById(id);
        if (!removed) {
            throw new MyException(20001, "評論刪除失敗或不存在");
        }
        return R.ok();
    }
}
